import { PageHeader, Card, List } from "antd";
import { Link } from "react-router-dom";
import { useEffect, useState } from "react";
import api from "../../api";
const { reqGetSomeNews, reqGetNews } = api;
import "./index.css";
interface dataType {
  auditState: 0 | 1 | 2;
  author: string;
  categoryId: number;
  content: string;
  createTime: number;
  id: number;
  publishState: 0 | 1 | 2;
  publishTime: number;
  region: string;
  roleId: number;
  star: number;
  title: string;
  view: number;
  category: slectType;
}
interface slectType {
  id: number;
  title: string;
  value: string;
}
type DataArray = Array<dataType>;

interface DataType {
  [name: string]: DataArray;
}

export default () => {
  const [data, useData] = useState<DataType>({});
  const [dataKey, useDataKey] = useState<Array<string>>([]);
  const getNew = async () => {
    const reuslt = (await reqGetSomeNews()) as unknown as DataArray;
    const data = reuslt.reduce<DataType>((value, item) => {
      if (value[item.category.title]) {
        value[item.category.title].push(item);
      } else {
        value[item.category.title] = [item];
      }
      return value;
    }, {});
    useData(data);
    useDataKey(Object.keys(data));
  };

  useEffect(() => {
    getNew();
    document.title = "全球新闻";
  }, []);
  const style2 = {
    width: "33.3%",
    padding: "10px",
    overflow: "hidden",
  };
  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        height: "100%",
        minHeight: "100vh",
        overflow: "hidden",
        padding: "10px",
      }}
    >
      <PageHeader title="全球大新闻" subTitle="全部新闻" />
      <div style={{ flex: 1, display: "flex", flexDirection: "column" }}>
        <div
          style={{
            width: "100%",
            flex: "50%",
            display: "flex",
            flexWrap: "wrap",
          }}
        >
          {dataKey.map((item, index) => {
            return (
              <div style={style2} key={index}>
                <Card title={item} bordered hoverable>
                  <List
                    size="small"
                    dataSource={data[item]}
                    pagination={{ pageSize: 2 }}
                    renderItem={(item) => {
                      return (
                        <List.Item>
                          <Link to={`/preview/${item.id}`}>{item.title}</Link>
                        </List.Item>
                      );
                    }}
                  />
                </Card>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};
